#include "../lib_include/CountDownLatch.h"

using namespace netlib;

CountDownLatch::CountDownLatch(int count)
  : mutex_(),
    condition_(mutex_),
    count_(count)           // 传入一个初始倒计时
{}

void CountDownLatch::wait() //等待
{
    MutexLockGuard lock(mutex_);    // 占有并锁住互斥锁
    while (count_ > 0)              // 等待计数器为0
        condition_.wait();
}

void CountDownLatch::countDown()    // 计数器减1
{
    MutexLockGuard lock(mutex_);
    --count_;
    if (count_ == 0)                // 计数器为0时通知所有线程
        condition_.notifyAll();
}

int CountDownLatch::getCount() const    // 返回当前计数器
{
    MutexLockGuard lock(mutex_);    // mutex_有mutable修饰，在const函数中能够被修改
    return count_;
}

